<?php
	session_start();
	require("access/connect.php");
	include("access/login_functions.php");
	include("user_type/system.php");
	
	$userID = intval($_SESSION['ID']);
	$keyword1 = trim($_POST['txtKey1']);
	$keyword2 = trim($_POST['txtKey2']);
	$img_ID = array(intval($_POST['image_ID0']),intval($_POST['image_ID1']));
	$rnd_number = $_POST['random'];
	$flag = array(0,0); // when flag[n]=0 keyword is incorrect otherwise it is correct.
	unset($_SESSION['captchaWarning']);
	unset($_SESSION['captchaSuccess']);

	if($rnd_number == 0){//Image on the left is the unknown image?
		//handle unknown image
		$insert_general = "INSERT INTO general_keywords(keyword, contentType, CID, UID) VALUES('$keyword1','img', $img_ID[0], $userID)";
		mysql_query($insert_general) or die('General Keyword insert failed. '.mysql_error());
		$update_kw = "UPDATE images_table SET kw1='$keyword1' WHERE CID = $img_ID[0]";
		
		$kw_cnt_query = "SELECT COUNT(*) FROM general_keywords WHERE keyword='$keyword1' AND contentType='img' AND CID = $img_ID[0]"; 
		$cnt_result=mysql_query($kw_cnt_query) or die('Query Failed'.mysql_error());
		$cnt_result= mysql_fetch_row($cnt_result);
		$cnter = intval($cnt_result[0]);

		
		if($cnter<3){	//keyword has never been typed for this image
			;
		}
		else{//keyword has been typed for this image before

			
			if($cnter >= 3){ //keyword has been typed for this image at least 3 times 
				mysql_query($update_kw)or die('New Keyword UPDATE failed'.mysql_error());
				
				if($cnter==3){
						/*Keyword becomes permanent. Add Credit to user*/
						$query = mysql_query("SELECT DISTINCT UID FROM general_keywords WHERE Keyword = '$keyword1' AND ContentType = 'img' AND CID =$img_ID[0]")
								or die("Users Could not be retreaved from DB. ".mysql_error());

						while($query_res = mysql_fetch_row($query)){
							$user = intval($query_res[0]);
							System::addCredits($user);
						}
					}
			}
			
		}
		$flag[0]=1;
		
		//handle known image
		$insert_general = "INSERT INTO general_keywords(keyword, contentType, CID, UID) VALUES('$keyword2','img', $img_ID[1], $userID)";
		mysql_query($insert_general) or die('General Keyword insert failed. '.mysql_error());
		
		$kw_cnt_query = "SELECT COUNT(*) FROM general_keywords WHERE keyword='$keyword2' AND contentType='img' AND CID = $img_ID[1]"; 
		$cnt_result = mysql_query($kw_cnt_query) or die("Error while getting keyword count for $keyword2  ");
		$cnt_result= mysql_fetch_row($cnt_result);
		$cnter = intval($cnt_result[0]);
		
		$update_kw = "UPDATE images_table SET kw1='$keyword2' WHERE CID = $img_ID[1]";
		
		$query=mysql_query("SELECT CID FROM images_table WHERE CID='$img_ID[1]' AND (KW1='$keyword2' OR KW2='$keyword2' OR KW3='$keyword2' OR KW4='$keyword2' OR KW5='$keyword2'
						OR KW6='$keyword2' OR KW7='$keyword2' OR KW8='$keyword2' OR KW9='$keyword2' OR KW10='$keyword2' OR KW11='$keyword2' OR KW12='$keyword2'
						OR KW13='$keyword2' OR KW14='$keyword2' OR KW15='$keyword2' OR KW16='$keyword2' OR KW17='$keyword2' OR KW18='$keyword2'
						OR KW19='$keyword2' OR KW20='$keyword2')")or die ('Query Failed'. mysql_error());
						
		if(mysql_num_rows($query) == NULL){//the keyword typed by user doesn't matches the image's list of keywords
										
			if($cnter<3){//keyword has never been typed for this image
				/**Wrong keyword. Reduce 0.2 from user credits	**/
				$numCredits = System::reduceCredits($userID);
				if ($numCredits <= 0.0)
					System::pendingBan($userID);
				
			}
			else{	//keyword has been typed for this image before
					
				
				if($cnter >= 3){ //keyword has been typed for this image at least 3 times 
				
					$query = mysql_query("SELECT KW20 FROM images_table WHERE CID = $img_ID[1] AND KW20 IS NOT NULL")or die ('Query Failed'. mysql_error());
					if(mysql_num_rows($query)==NULL){//All the keyword fields for a given picture are not yet filled
						for($i=2; $i<=20; $i++){
							$kw = 'KW'."$i";
							$update_kw = "UPDATE images_table SET $kw='$keyword2' WHERE CID = $img_ID[1]";
							
							$query=mysql_query("SELECT $kw FROM images_table where CID=$img_ID[1] AND $kw IS NOT NULL")or die ('Query Failed'. mysql_error());
							if(mysql_num_rows($query)==NULL){//This keyword field is available?
								mysql_query($update_kw)or die("Keyword $kw could not be updated");
								break;
							}								
						}	
						
					}
					if($cnter==3){						
						/*Keyword becomes permanent. Add Credit to user*/
						$query = mysql_query("SELECT DISTINCT UID FROM general_keywords WHERE Keyword = '$keyword2' AND ContentType = 'img' AND CID =$img_ID[1]")
								or die("Users Could not be retreaved from DB. ".mysql_error());
						
						while($query_res = mysql_fetch_row($query)){
							$user = intval($query_res[0]);
							System::addCredits($user);
						}
					}
					//**Success**//
					$flag[1]=1;	
					$_SESSION['captchaSuccess'] = true;
				}
			}
		}
		else {
			//***Success**//
			$flag[1]=1;
			$_SESSION['captchaSuccess'] = true;
		}
	}
	else{//********Image on the left is the known image*********//
		//handle known image
		
		$insert_general = "INSERT INTO general_keywords(keyword, contentType, CID, UID) VALUES('$keyword1','img', $img_ID[1], $userID)";
		mysql_query($insert_general) or die('General Keyword insert failed. '.mysql_error());
		$update_kw = "UPDATE images_table SET kw1='$keyword1' WHERE CID = $img_ID[1]";
		$kw_cnt_query = "SELECT COUNT(*) FROM general_keywords WHERE keyword='$keyword1' AND contentType='img' AND CID = $img_ID[1]"; 
		$cnt_result = mysql_query($kw_cnt_query) or die("Error while getting keyword count for $keyword1  ");
		$cnt_result= mysql_fetch_row($cnt_result);
		$cnter = intval($cnt_result[0]);
		
		$query = mysql_query("SELECT CID FROM images_table WHERE CID=$img_ID[1] AND (KW1='$keyword1' OR KW2='$keyword1' OR KW3='$keyword1' OR KW4='$keyword1' OR KW5='$keyword1'
						OR KW6='$keyword1' OR KW7='$keyword1' OR KW8='$keyword1' OR KW9='$keyword1' OR KW10='$keyword1' OR KW11='$keyword1' OR KW12='$keyword1'
						OR KW13='$keyword1' OR KW14='$keyword1' OR KW15='$keyword1' OR KW16='$keyword1' OR KW17='$keyword1' OR KW18='$keyword1'
						OR KW19='$keyword1' OR KW20='$keyword1')") or die ('Query Failed'. mysql_error());
		if(mysql_num_rows($query) == NULL){//the keyword typed by user doesn't matches the image's list of keywords
				
			if($cnter<3){//keyword has never been typed for this image
				 /**Wrong keyword. Reduce 0.2 from user credits	**/
				 System::reduceCredits($userID);
				 if ($numCredits <= 0.0)
					System::pendingBan($userID);
			}
			else{	//keyword has been typed for this image before
						
				if($cnter >= 3){ //keyword has been typed for this image at least 3 times 
					$query = mysql_query("SELECT KW20 FROM images_table WHERE CID = $img_ID[1] AND KW20 IS NOT NULL") or die ('Query Failed'. mysql_error());
					if(mysql_num_rows($query)==NULL){//All the keyword fields for a given picture are not filled
						for($i=2; $i<=20; $i++){
							$kw = 'KW'."$i";
							$update_kw = "UPDATE images_table SET $kw='$keyword1' WHERE CID = $img_ID[1]";
							
							$query= mysql_query("SELECT $kw FROM images_table where CID=$img_ID[1] AND $kw IS NOT NULL")or die ('Query Failed'. mysql_error());
							if(mysql_num_rows($query)==NULL){//This keyword field is available?
								mysql_query($update_kw)or die("Keyword $kw could not be updated");
								break;
							}								
						}			
					}
					if($cnter==3){
						/*Keyword becomes permanent. Add Credit to user*/
						$query = mysql_query("SELECT DISTINCT UID FROM general_keywords WHERE Keyword = '$keyword1' AND ContentType = 'img' AND CID =$img_ID[1]")
								or die("Users Could not be retreaved from DB. ".mysql_error());
						
						while($query_res = mysql_fetch_row($query)){
							$user = intval($query_res[0]);
							System::addCredits($user);
						}	
					}
					//**Success**//
					$flag[1]=1;
				}
			}
		}
		else {
		//***Success**//
		$flag[1] = 1;
		}
		//************handle unknown image*****************//
		$insert_general = "INSERT INTO general_keywords(keyword, contentType, CID, UID) VALUES('$keyword2','img', $img_ID[0], $userID)";
		mysql_query($insert_general) or die('General Keyword insert failed. '.mysql_error());
		$update_kw = "UPDATE images_table SET kw1='$keyword2' WHERE CID = $img_ID[0]";
		
		$kw_cnt_query = "SELECT COUNT(*) FROM general_keywords WHERE keyword='$keyword2' AND contentType='img' AND CID = $img_ID[0]"; 
		$cnt_result= mysql_query($kw_cnt_query)or die ('Query Failed'. mysql_error());
		$cnt_result= mysql_fetch_row($cnt_result);
		$cnter = intval($cnt_result[0]);
		
		if($cnter<3){	//keyword has never been typed for this image
			;
		}
		else{//keyword has been typed for this image before
						
			if($cnter >= 3){ //keyword has been typed for this image at least 3 times 			
				mysql_query($update_kw)or die('New Keyword UPDATE failed. '.mysql_error());
				
				if($cnter==3){
						/*Keyword becomes permanent. Add Credit to user*/
						$query = mysql_query("SELECT DISTINCT UID FROM general_keywords WHERE Keyword = '$keyword2' AND ContentType = 'img' AND CID =$img_ID[0]")
								or die("Users Could not be retreaved from DB. ".mysql_error());

						while($query_res = mysql_fetch_row($query)){
							$user = intval($query_res[0]);
							System::addCredits($user);
						}
					}
			}
		}
		$flag[0]=1;
	}
	
	if($flag[0]+$flag[1] == 2){
		send_to_page("search_Result.php");

	//	echo "Keyword input was correct. Thank You.";
		}
	else{
		$_SESSION['captchaWarning'] =  "<center>Wrong keyword input. 0.2 points will be deducted from your credits.</center><br>";
	//	echo "<center><a href=\"home.php\">Go to Home Page</a></center>";
		send_to_page("home.php");
		}
	@mysql_connect(close);
?>